import { Context } from 'koa'
import { handleCreateToken, insert, select, success, update } from '../utils/index'
import bcrypt from 'bcryptjs'

export class LoginController {
  static async login(ctx: Context) {
    const { username, password } = ctx.request.body as any
    const [rows]: [any, any] = (await select('users', { username })) as [any, any]
    if (!rows.length) {
      throw new Error('用户不存在')
    }
    if (!rows[0].password && password) {
      const hashedPassword = await bcrypt.hash(password, 10)
      await update('users', { id: rows[0].id }, { password: hashedPassword })
    }
    if (rows[0].password && !bcrypt.compareSync(password, rows[0].password)) {
      throw new Error('密码错误')
    }
    await handleCreateToken(ctx, username)
    ctx.body = success(ctx, {
      ...rows[0],
      password: undefined,
      userId: rows[0].id
    })
  }
  static async loginOut(ctx: Context) {
    const { develop_branch_id } = ctx.request.body as any
    await insert('black_tokens', { token: ctx.cookies.get('token') })
    const [rows]: [any, any] = (await select('branches', {
      id: develop_branch_id,
      coding_developer: ctx.request.headers.nickname
    })) as [any, any]
    rows.length &&
      (await update('branches', { id: develop_branch_id }, { coding_developer: '', coding_developer_token: '' }))
    ctx.body = success(ctx, {})
  }
}
